// SlagCar/WaybillDetail/WaybillDetail.js
import {config} from "../../utils/config";
import {imgCompress} from "../../utils/img";

const req = require('../../utils/request');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    system_id: wx.getStorageSync('system_id') || 1164,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,

    rowData: {},
    // 查询接口V3，只返回有用字段
    rowFieldList: ['row_id','Order_No','reference1_car','reference1_driver','driver_price','reference1_goods','reference1_all_delivery','reference1_muck_order_main',
      'driver_start_time','Order_client_ID','gongdilianxiren','gongdilianxidianhua','driver_start_addr','driver_start_img','driver_start_mark', 'driver_start_latitude','driver_start_longitude','reference1_all_destination',
      'driver_end_time','destination_client','xiaonachanglianxiren','xiaonachanglianxidianhua','driver_end_addr','driver_end_img','driver_end_mark',
      'fill_order_img','fill_excavator_img','fill_order_no','fill_excavator_no','fill_excavator_no_end','fill_excavator_img_end','is_exceptional_mud_head','is_exceptional_mud_tail','exceptional_mud_tail_img','staff_mark',
      'need_fill_order_no','need_fill_excavator_img','need_fill_order_img','need_fill_excavator_img_end','need_fill_order_img_end','need_fill_order_no_end',
      'ShenQingQuXiaoBiaoShi','ShenHeQuXiaoYuanMing','ShenHeQuXiaoZhuangTai','ShenHeQuXiaoBuTongGuoYuanYin','ShenHeQuXiaoShiJian',
      'TuZhiWeiZhi','ZhiDingXieHuoDiZhi','ZhiDingXieHuoDiZhiXiaoNaChang','YanShiXieHuoFenZhongShu','ZhiDingXieHuoJieShuZhaoPian','WuShuiYinSiJiJieShuZhaoPian'
    ],

    field: [
      /*{field_id: 'driver_start_time',label: '当前时间',isDisabled: true,type: 'text'},
      {field_id: 'driver_start_addr',label: '当前位置',isDisabled: true,type: 'text'},
      {field_id: 'driver_start_longitude',label: '经度',isDisabled: true,type: 'text'},
      {field_id: 'driver_start_latitude',label: '纬度',isDisabled: true,type: 'text'},
      {field_id: 'driver_start_img',label: '图片',type: 'picture'},
      {field_id: 'driver_start_mark',label: '备注',type: 'textarea'},*/

      {field_id: 'driver_end_time',label: '当前时间',isDisabled: true,type: 'text'},
      {field_id: 'driver_end_addr',label: '当前位置',isDisabled: true,type: 'text'},
      {field_id: 'driver_end_longitude',label: '经度',isDisabled: true,type: 'text'},
      {field_id: 'driver_end_latitude',label: '纬度',isDisabled: true,type: 'text'},
      {field_id: 'driver_end_img',label: '图片',type: 'picture'},
      {field_id: 'driver_end_mark',label: '备注',type: 'textarea'},
      // {field_id: 'is_exceptional_mud_tail',label: '是否异常泥尾',type: 'splc'},
    ],
    defData: {},
    inputData: {},
    authField: {},

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项

    status: 2,   //0 已接单未开始-显示【开始任务】 1 已开始未结束-显示【结束任务】 2 已结束-不显示按钮

    show: false,

    showDest: false, //  显示更换泥尾弹窗
    showDestIpt: false, //显示更换泥尾输入弹窗
    showPicker: false,  //显示应收应付选择
    columns: ['应收','应付'],
    defaultPickerValue: 0,  //默认应收选项
    destinationList: [], //更换泥尾选项
    selectedDest: '',
    changeDestValue: {
      destination_payment: '应付',
      driver_payment: '应付',
      extra_payment: '应付',
    },

    isEdit: false,  // 字段是否编辑


    // 取消运单申请
    cancelShow: false,
    cancelField: [
      {field_id: 'ShenQingQuXiaoYuanYin',label: '取消原因',type: 'textarea',is_null: true},
      {field_id: 'ShenQingQuXiaoZhaoPian',label: '申请取消照片',type: 'picture',is_null: true},
      {field_id: 'ShenHeQuXiaoJieShouYuanHao',label: '审核取消接收员',type: 'picklist',optionList: [],optionId: 'user_id',optionName: 'user_name'},
    ],
    cancelData: {},
    cancelUserList: null


  },

  /**
   * 初始获取运单信息
   * 1、填充运单信息
   * 2、判断运单状态
   * 3、根据运单状态显示不同按钮、弹窗标题，设置弹窗字段项
   */
  getRowDataOld(){
    return new Promise(resolve => {
      let url = 'DynamicQuery/query_dynamic_v2',
        {row_id} = this.data,
        post = {row_id,table_id: 'muck_waybill_main'};
      wx.showLoading({mask: true})
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading();
        let data = res.data.row && res.data.row[0];
        if (data){
          let driver_row_id = wx.getStorageSync('driver_row_id');
          let rowData = data.entity[0],
            //判断运单状态：1、当前登录司机为当前订单指派人员 2、开始时间为空则未开始（0）  3、开始时间不为空结束时间为空:已开始（1） 4、开始时间结束时间不为空: 已结束（2）
            status = driver_row_id == rowData.reference1_driver ? (rowData.driver_start_time && rowData.driver_end_time ? 2 : rowData.driver_start_time ? 1 : 0) : 3,
            startField = [{field_id: 'driver_start_time',label: '当前时间',isDisabled: true,type: 'text'},
              {field_id: 'driver_start_addr',label: '当前位置',isDisabled: true,type: 'text'},
              // {field_id: 'driver_start_longitude',label: '经度',isDisabled: true,type: 'text'},
              // {field_id: 'driver_start_latitude',label: '纬度',isDisabled: true,type: 'text'},
              /** 231216 liang 注释
              {field_id: 'driver_start_img',label: '装货照片',type: 'picture',allowUpload:false,compress: true,is_null: false,watermark: () => this.getWatermark()},
              {field_id: 'fill_order_no',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no},
              {field_id: 'fill_order_img',label: '运单照片',type: 'picture',allowUpload:false,is_null: !rowData.need_fill_order_img,compress: true,watermark: () => this.getWatermark()},
              {field_id: 'fill_excavator_no',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"picklist","fieldName":"cheliangyongtu","value":"挖机","operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no},
              {field_id: 'fill_excavator_img',label: '挖机照片',type: 'picture',allowUpload:false,is_null: !rowData.need_fill_excavator_img,compress: true,watermark: () => this.getWatermark()},
              {field_id: 'driver_start_wait_time',label: '等待时间(小时)',type: 'num',is_null: true},
              */
              // 231216 liang 按方通张小姐要求，顺序调整为 装货照片、挖机号、挖机照片、运单照片、运单号，删除 等待时间(小时)；易工要求 挖机号 增加启用标示 过滤条件
              {field_id: 'driver_start_img',label: '装货照片',type: 'picture',is_take_a_photo :true,compress: true,is_null: false,watermark: () => this.getWatermark()},
              {field_id: 'fill_excavator_no',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"AND","fieldName":"cheliangyongtu","value":"挖机","operator":"="},{"filterType":"bit","type":"AND","fieldName":"is_used","value":true,"operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no, noAdd: true,pageLimit: 1000},
              {field_id: 'fill_excavator_img',label: '挖机照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_excavator_img,compress: true,watermark: () => this.getWatermark()},
              {field_id: 'fill_order_img',label: '运单照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_order_img,compress: true,watermark: () => this.getWatermark()},
              {field_id: 'fill_order_no',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no},
              // 231216 end
              {field_id: 'driver_start_mark',label: '备注',type: 'textarea'}],
            endField = [{field_id: 'driver_end_time',label: '当前时间',isDisabled: true,type: 'text'},
              {field_id: 'driver_end_addr',label: '当前位置',isDisabled: true,type: 'text'},
              // {field_id: 'driver_end_longitude',label: '经度',isDisabled: true,type: 'text'},
              // {field_id: 'driver_end_latitude',label: '纬度',isDisabled: true,type: 'text'},
              {field_id: 'driver_end_img',label: '卸货照片',type: 'picture',is_take_a_photo :true,is_null: false,compress: true,watermark:  () => this.getWatermark()},
              // {field_id: 'fill_order_no',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no},
              // {field_id: 'fill_order_img',label: '运单照片',type: 'picture',is_null: !rowData.need_fill_order_img},
              /** 231216 liang 注释
              {field_id: 'fill_excavator_no_end',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"picklist","fieldName":"cheliangyongtu","value":"挖机","operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no},
              */
              // 231216 liang 挖机号 是否必填按 need_fill_excavator_no_end 填写值；挖机照片 是否必填按 need_fill_excavator_img_end 填写值；易工要求 挖机号 增加启用标示 过滤条件
              {field_id: 'fill_excavator_no_end',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"AND","fieldName":"cheliangyongtu","value":"挖机","operator":"="},{"filterType":"bit","type":"AND","fieldName":"is_used","value":true,"operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no_end,noAdd: true,pageLimit: 1000},
              //
              // {field_id: 'fill_excavator_no_end',label: '挖机号',type: 'text',is_null: !rowData.need_fill_excavator_no_end},
              {field_id: 'fill_excavator_img_end',label: '挖机照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_excavator_img_end},

              /*241120 增加增加运单号，泥尾运单照片*/
              {field_id: 'fill_order_no_end',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no_end},
              {field_id: 'fill_order_img_end',label: '运单照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_order_img_end,compress: true,watermark: () => this.getWatermark()},
              /*241120 end*/

              /** 231216 liang 按方通张小姐要求，删除 等待时间(小时)、台班(小时)、趟次、方数 填写项
              {field_id: 'driver_end_wait_time',label: '等待时间(小时)',type: 'num',is_null: true},
              {field_id: 'machine_team',label: '台班(小时)',type: 'num',is_null: true},
              {field_id: 'fill_transport_times',label: '趟次',type: 'num',is_null: !rowData.need_fill_transport_times},
              {field_id: 'fill_square_number',label: '方数',type: 'num',is_null: !rowData.need_fill_square_number},
              */
              {field_id: 'driver_end_mark',label: '备注',type: 'textarea'},
              // {field_id: 'is_exceptional_mud_tail',label: '是否异常泥尾',type: 'splc'}
              ]

          this.setData({rowData,inputData: {},status,field: status === 0 ? startField : endField});
          status == 1 && this.getDestinationAll();
          status == 0 && this.getDeliveryAll();
        }
        resolve();
      })

    })
  },
  getRowData(){
    return new Promise(resolve => {
      let url = 'DynamicQuery/query_dynamic_v3',
        {row_id,rowFieldList} = this.data,
        field_list = rowFieldList.join(',');
      wx.showLoading({mask: true});
      let where = [{CompareWith:"muck_waybill_main.row_id",Operator:"=",CompareValue:row_id,"or":0}]
      this.getCustomData('muck_waybill_main',where,field_list).then(row =>{
        wx.hideLoading();
        let data = row && row[0];
        if (data){
          this.initField(data);
        }
        resolve();
      })

    })
  },
  initField(data){
    // 获取运单权限
    this.getAuthorityList('muck_waybill_main').then(res =>{
      this.setData({
        auth: res,
      });
      // 获取订单设置
      this.getOrderMain(data).then(() =>{
        // 控制装卸货字段
        setField()
      })
    })
    const This = this;
    function setField() {
      let {orderMainData,inputData,auth} = This.data
      let driver_row_id = wx.getStorageSync('driver_row_id');
      let rowData = data,
        //判断运单状态：1、当前登录司机为当前订单指派人员 2、开始时间为空则未开始（0）  3、开始时间不为空结束时间为空:已开始（1） 4、开始时间结束时间不为空: 已结束（2）
        status = driver_row_id == rowData.reference1_driver ? (rowData.driver_start_time && rowData.driver_end_time ? 2 : rowData.driver_start_time ? 1 : 0) : 3,
        startField = [{field_id: 'driver_start_time',label: '当前时间',isDisabled: true,type: 'text'},
          {field_id: 'driver_start_addr',label: '当前位置',isDisabled: true,type: 'text'},
          // {field_id: 'driver_start_longitude',label: '经度',isDisabled: true,type: 'text'},
          // {field_id: 'driver_start_latitude',label: '纬度',isDisabled: true,type: 'text'},
          /** 231216 liang 注释
           {field_id: 'driver_start_img',label: '装货照片',type: 'picture',allowUpload:false,compress: true,is_null: false,watermark: () => this.getWatermark()},
           {field_id: 'fill_order_no',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no},
           {field_id: 'fill_order_img',label: '运单照片',type: 'picture',allowUpload:false,is_null: !rowData.need_fill_order_img,compress: true,watermark: () => this.getWatermark()},
           {field_id: 'fill_excavator_no',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"picklist","fieldName":"cheliangyongtu","value":"挖机","operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no},
           {field_id: 'fill_excavator_img',label: '挖机照片',type: 'picture',allowUpload:false,is_null: !rowData.need_fill_excavator_img,compress: true,watermark: () => this.getWatermark()},
           {field_id: 'driver_start_wait_time',label: '等待时间(小时)',type: 'num',is_null: true},
           */
          // 231216 liang 按方通张小姐要求，顺序调整为 装货照片、挖机号、挖机照片、运单照片、运单号，删除 等待时间(小时)；易工要求 挖机号 增加启用标示 过滤条件
          {field_id: 'driver_start_img',label: '装货照片',type: 'picture',is_take_a_photo :true,compress: true,is_null: false,watermark: () => This.getWatermark()},
          {field_id: 'fill_excavator_no',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"AND","fieldName":"cheliangyongtu","value":"挖机","operator":"="},{"filterType":"bit","type":"AND","fieldName":"is_used","value":true,"operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no, noAdd: true,pageLimit: 1000},
          {field_id: 'fill_excavator_img',label: '挖机照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_excavator_img,compress: true,watermark: () => This.getWatermark()},
          {field_id: 'fill_order_img',label: '运单照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_order_img,compress: true,watermark: () => This.getWatermark()},
          {field_id: 'fill_order_no',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no},
          // 231216 end
          {field_id: 'driver_start_mark',label: '备注',type: 'textarea'}],
        endField = [{field_id: 'driver_end_time',label: '当前时间',isDisabled: true,type: 'text'},
          {field_id: 'driver_end_addr',label: '当前位置',isDisabled: true,type: 'text'},
          // {field_id: 'driver_end_longitude',label: '经度',isDisabled: true,type: 'text'},
          // {field_id: 'driver_end_latitude',label: '纬度',isDisabled: true,type: 'text'},
          {field_id: 'driver_end_img',label: '卸货照片',type: 'picture',is_take_a_photo :true,is_null: false,compress: true,watermark:  () => This.getWatermark(),needOriginImg: true},
          // {field_id: 'fill_order_no',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no},
          // {field_id: 'fill_order_img',label: '运单照片',type: 'picture',is_null: !rowData.need_fill_order_img},
          /** 231216 liang 注释
           {field_id: 'fill_excavator_no_end',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"picklist","fieldName":"cheliangyongtu","value":"挖机","operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no},
           */
          // 231216 liang 挖机号 是否必填按 need_fill_excavator_no_end 填写值；挖机照片 是否必填按 need_fill_excavator_img_end 填写值；易工要求 挖机号 增加启用标示 过滤条件
          {field_id: 'fill_excavator_no_end',label: '挖机号',type: 'reference1',referenceFilterCondition:`{"filters":[{"filterType":"picklist","type":"AND","fieldName":"cheliangyongtu","value":"挖机","operator":"="},{"filterType":"bit","type":"AND","fieldName":"is_used","value":true,"operator":"="}],"type":"AND"}`,mainEntity: 'e_cheliangziliaobiao',showFields: 'chelianghaoma',is_null: !rowData.need_fill_excavator_no_end,noAdd: true,pageLimit: 1000},
          //
          // {field_id: 'fill_excavator_no_end',label: '挖机号',type: 'text',is_null: !rowData.need_fill_excavator_no_end},
          {field_id: 'fill_excavator_img_end',label: '挖机照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_excavator_img_end},

          /*241120 增加增加运单号，泥尾运单照片*/
          {field_id: 'fill_order_no_end',label: '运单号',type: 'text',is_null: !rowData.need_fill_order_no_end},
          {field_id: 'fill_order_img_end',label: '运单照片',type: 'picture',is_take_a_photo :true,is_null: !rowData.need_fill_order_img_end,compress: true,watermark: () => This.getWatermark()},
          /*241120 end*/

          /** 231216 liang 按方通张小姐要求，删除 等待时间(小时)、台班(小时)、趟次、方数 填写项
           {field_id: 'driver_end_wait_time',label: '等待时间(小时)',type: 'num',is_null: true},
           {field_id: 'machine_team',label: '台班(小时)',type: 'num',is_null: true},
           {field_id: 'fill_transport_times',label: '趟次',type: 'num',is_null: !rowData.need_fill_transport_times},
           {field_id: 'fill_square_number',label: '方数',type: 'num',is_null: !rowData.need_fill_square_number},
           */
          {field_id: 'driver_end_mark',label: '备注',type: 'textarea'},
          // {field_id: 'is_exceptional_mud_tail',label: '是否异常泥尾',type: 'splc'}
        ],
        authField = {};
      // 订单主表数据
      if (orderMainData){
        // 装货操作，需要填工地位置
        if (status === 0 && orderMainData.XuYaoTianTuZhiWeiZhi){
          let authObj = auth.find(ite => ite.function_id === 'TuZhiWeiZhi');
          if (authObj && authObj.is_see) {
            let label = authObj.function_name || '图纸位置';  // 字段名
            authField.TuZhiWeiZhi = {field_id: 'TuZhiWeiZhi',label}
            let str = orderMainData.TuZhiWeiZhiLieBiao && orderMainData.TuZhiWeiZhiLieBiao.replace(/，/g, ',') || '',
              arr = str && str.split(',') || [],
              options = [];
            arr.forEach(item => options.push({label: item}));
            let field = {field_id: 'TuZhiWeiZhi',label,type: 'picklist',is_null: false,optionList: options};
            startField.splice(startField.length - 1,0,field)
            authField.TuZhiWeiZhi = field

          }}
        //  卸货
        if (status !== 0 ) {
          let otherField = [];
          // 卸货操作，指定卸货地址
          if (orderMainData.ZhiDingXieHuoDiZhi) {
            let authObj = auth.find(ite => ite.function_id === 'ZhiDingXieHuoDiZhi');
            if (authObj && authObj.is_see) {
              let label = authObj.function_name || '指定卸货地址';  // 字段名
              let field = {field_id: 'ZhiDingXieHuoDiZhi',label,isDisabled: true,type: 'text'}
              otherField.push(field);
              authField.ZhiDingXieHuoDiZhi = field
            }
            inputData.ZhiDingXieHuoDiZhi = orderMainData.ZhiDingXieHuoDiZhi
            inputData.ZhiDingXieHuoJingDu = orderMainData.ZhiDingXieHuoJingDu
            inputData.ZhiDingXieHuoWeiDu = orderMainData.ZhiDingXieHuoWeiDu;

            let authObj2 = auth.find(ite => ite.function_id === 'ZhiDingXieHuoJieShuZhaoPian');
            if (authObj2 && authObj2.is_see) {
              let label = authObj2.function_name || '指定卸货结束照片';  // 字段名
              let field = {field_id: 'ZhiDingXieHuoJieShuZhaoPian',label,isDisabled: true,type: 'picture'}
              otherField.push(field);
              authField.ZhiDingXieHuoJieShuZhaoPian = field
            }
          }
          // 卸货操作，指定卸货地址消纳场
          if (orderMainData.ZhiDingXieHuoDiZhiXiaoNaChang) {
            let authObj = auth.find(ite => ite.function_id === 'ZhiDingXieHuoDiZhiXiaoNaChang');
            if (authObj && authObj.is_see) {
              let label = authObj.function_name || '指定卸货地址消纳场';  // 字段名
              let field = {field_id: 'ZhiDingXieHuoDiZhiXiaoNaChang;value',label,isDisabled: true,type: 'text'}
              otherField.push(field,)
              authField.ZhiDingXieHuoDiZhiXiaoNaChang = field
            }
            inputData.ZhiDingXieHuoDiZhiXiaoNaChang = orderMainData.ZhiDingXieHuoDiZhiXiaoNaChang
            inputData['ZhiDingXieHuoDiZhiXiaoNaChang;value'] = orderMainData['ZhiDingXieHuoDiZhiXiaoNaChang;value']
          }
          // 卸货操作，延时卸货分钟数
          if (orderMainData.YanShiXieHuoFenZhongShu) {
            let authObj = auth.find(ite => ite.function_id === 'ZhiDingXieHuoJieShuShiJian');
            if (authObj && authObj.is_see) {
              let label = authObj.function_name || '指定卸货结束时间';  // 字段名
              let field = {field_id: 'ZhiDingXieHuoJieShuShiJian',label,isDisabled: true,type: 'text'}
              otherField.push(field)
              authField.YanShiXieHuoFenZhongShu = field
            }
          }
          otherField.length && endField.splice(endField.length - 1,0,...otherField)
        }
      }
      This.setData({rowData,inputData,authField,status,field: status === 0 ? startField : endField});
      status == 1 && This.getDestinationAll();
      status == 0 && This.getDeliveryAll();
    }
  },

  bindSwitchChange(e){
    let value = e.detail;
    this.setData({['inputData.is_exceptional_mud_tail']: value})
    let {field} = this.data;
    if (value){
      field.push({field_id: 'exceptional_mud_tail_img',label: '异常泥尾照片',type: 'picture'},)
    }else {
      field.pop();
    }
    this.setData({field})
  },

  //开始任务，结束任务
  bindShowSubmit(){
    this.setData({show: true,})
    // this.initData();
  },
  bindShow(e){
    let {type} = e.currentTarget.dataset;
    this.setData({[type]: true})

  },
  bindClose(){
    this.setData({show:false,showPicker: false,showDest: false,cancelShow: false})
  },
  // 关闭更改泥尾弹窗
  bindCloseDestIpt(){
    this.setData({showDestIpt: false})
  },
  bindSubmit(){
    if (this.data.loading) return
    this.data.loading = true;
    wx.showLoading({mask: true});
    let {rowData,status} = this.data;
    this.data.validObj = {}
    this.setData({
      validFlag: !this.data.validFlag,
    });

    let formObj = {...this.data.inputData},
      validObj = this.data.validObj;
    this.validForm(validObj).then(async valid => {
      if(valid) { // 表单验证通过
        console.log('表单验证通过', formObj);
        formObj.row_id = rowData.row_id;
        if (status == 0) {
          formObj.waybill_state = '已装货';
          //判断是否泥头异常
          await this.abnormalDeli(rowData.reference1_all_delivery).then(res => {
            formObj.is_exceptional_mud_head = res;
          });
        }
        if (status == 1) {
          formObj.waybill_state = '已卸货';
          const now = new Date(),
            year = now.getFullYear();
          let month = now.getMonth() + 1
          month = month < 10 ? '0' + month : month;
          formObj.account_period = year + '' + month;//卸货时增加会计期
          //判断是否泥尾异常
          await this.abnormalDest(rowData.reference1_all_destination).then(res => {
            formObj.is_exceptional_mud_tail = res;
          })
        }
        //提交数据过滤[**;value]字段
        wx.$each(formObj,(key,val)=>{
          if (key.indexOf(';') >= 0){ delete formObj[key] }
        });
        console.log(formObj);
        this.submitData('muck_waybill_main', formObj).then(res => {
          this.data.loading = false;
           wx.$toast('提交成功');
           this.getRowData();
           this.setData({show: false});
           //结束提交审核--231229 yan 取消提交审批
           /*if (status == 1){
              this.bindSubmitApprove();
           }*/
         })

      } else {  // 表单验证不通过
        console.log('表单验证不通过')
        wx.$toast('必填项不能为空！')
        this.data.loading = false;
      }
    })
  },
  //显示更换泥尾
  bindShowDest(){
    let {destinationList,rowData} = this.data;
    if (!destinationList.length){
      this.getDestinationList(rowData.reference1_muck_order_main).then(() => {
        this.setData({showDest: true})
      })
    } else {
      this.setData({showDest: true})
    }
  },
  bindSelectDestination(e){
    let {index} = e.currentTarget.dataset,
      {destinationList } = this.data,
      data = destinationList[index];
    this.setData({
      selectedDest: destinationList[index],
      showDest: false,
      [`changeDestValue.reference1_all_destination`]: data.reference1_all_destination,
      [`changeDestValue.destination_client`]: data.Order_client_ID,
      [`changeDestValue.construction_payment`]: data.construction_payment,
      [`changeDestValue.construction_price`]: data.construction_price,
      [`changeDestValue.destination_payment`]: data.destination_payment,
      [`changeDestValue.destination_price`]: data.Order_amount,
      [`changeDestValue.driver_payment`]: data.driver_payment,
      [`changeDestValue.driver_price`]: data.driver_price,
      [`changeDestValue.extra_payment`]: data.extra_payment,
      [`changeDestValue.extra_price`]: data.extra_price,
      [`changeDestValue.xiaonachanglianxiren`]: data.xiaonachanglianxiren,
      [`changeDestValue.xiaonachanglianxidianhua`]: data.xiaonachanglianxidianhua,
      [`changeDestValue.need_fill_excavator_img_end`]: data.need_fill_excavator_img_end,
      [`changeDestValue.need_fill_excavator_no_end`]: data.need_fill_excavator_no_end,
      [`changeDestValue.need_fill_order_no_end`]: data.need_fill_order_no_end,
      [`changeDestValue.need_fill_order_img_end`]: data.need_fill_order_img_end,
    })
  },
  //确认选择选择器
  bindConfirmPicker(e){
    let {value} = e.detail
    this.setData({
      showPicker: false,
      ['changeDestValue.destination_payment']: value
    });

  },
  // 搜索
  bindSearch(e){
    let {type} = e.currentTarget.dataset,
      val = e.detail,
      obj = {
        delivery: {listName: 'deliveryList',fieldName: ['delivery_name','Order_client_ID;value']},
        destination: {listName: 'destinationList',fieldName: ['destination_name','Order_client_ID;value']},
        driver: {listName: 'driverList',fieldName: 'jiashiyuanxingming'},
        goods: {listName: 'goodsList',fieldName: 'goods_name'}
      },
      {listName,fieldName} = obj[type],
      list = this.data[listName];
    list.forEach(item => {
      let text = item[fieldName];
      if (typeof fieldName === 'object'){
        text = [];
        fieldName.forEach(ite => {item[ite] && text.push(item[ite])});
        text = text.join('');
      }
      item.isHide = text.indexOf(val) < 0
    })
    console.log(list);
    this.setData({[listName]: list});
  },

  //输入框修改
  bindChangeInput(e){
    let {value} = e.detail,
      {field} = e.currentTarget.dataset;
    this.setData({[`changeDestValue.${field}`]: value});
  },
  //确定提交更换泥尾
  confirmDest(){
    let {selectedDest,rowData,changeDestValue} = this.data,
      url = 'DynamicUpdate/dynamic_update_v3',
      obj2 = {
        reference1_all_destination: '请选择消纳场',
        // xiaonachanglianxiren: '请输入消纳场联系人',
        // xiaonachanglianxidianhua: '请输入消纳场联系电话',
        // destination_price: '请输入消纳场价格',
      };
    let flag = this.checkRequired(changeDestValue,obj2);
    if (!flag) return;

    let post = {
      table: {
        table_id: 'muck_waybill_main',
        entitys: [
          {
            details: [],
            entity: {
              ...changeDestValue,
              row_id: rowData.row_id
            }
          }
        ]
      }
    };
    wx.showLoading({mask: true})
    wx.$post(3,url,post).then(res => {
      if (res.errcode != 0) return;
      wx.$toast('更换成功');
      setTimeout(() => {
        this.getRowData();
        this.setData({showDestIpt: false})
      },500)
    })
  },
  //获取泥尾列表
  getDestinationList(id){
    return new Promise(resolve => {

      wx.showLoading({mask: true});
      let url = 'DynamicQuery/query_dynamic_v3',
        post = {
          "oby":"muck_order_assign_destination.row_id",
          "table_id":"muck_order_assign_destination",
          "page":1,"limit":0,
          "SearchWhere":{"filters":[{"CompareWith":"muck_order_assign_destination.parent_row_id","Operator":"=","CompareValue": id,"or":0}],type: 'and'}
      };
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading();
        let data = res.data.row || [];
        data = data.filter(item => item.is_used);
        this.setData({destinationList: data})
        resolve();
      })
    })


  },

  //取消运单
  cancelWaybill(){
    let {rowData} = this.data;
    wx.showModal({
      title: '取消运单',
      content: '确定取消运单？',
      success: (res) => {
      if(res.confirm) {
        wx.showLoading({mask: true});
        /*setTimeout(() => {
          wx.$toast('取消成功');
        },500)*/
        this.submitData('muck_waybill_main', {row_id: rowData.row_id,is_used: false}).then(res => {
          wx.$toast('取消成功');
          wx.redirectTo({url: '/SlagCar/WaybillList/WaybillList'})
          // this.getRowData();
        })
      }
    },
    })
  },

  //提交修改数据
  submitData(table_id,data){
    let url = 'DynamicUpdate/dynamic_update_v3',
      post = {table:{table_id,entitys: [
            {
              details: [],
              entity: data
            }
          ]}};
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res =>{
        this.data.loading = false;
        if (res.errcode != 0) return;
        resolve();
      })
    })
  },



  //初始化数据
  initData(){
    return new Promise(resolve => {
      let {status,orderMainData} = this.data,
        target = status === 0 ? 'start' : 'end';

      let now = new Date(),
        nowTime = wx.$util.formatDate(now,'yyyy-MM-dd HH:mm'),
        obj = {
          [`inputData.driver_${target}_time`]: nowTime,
          nowTime,
        }
      if (target === 'end' && orderMainData && orderMainData.YanShiXieHuoFenZhongShu) {
        let delay = now.getTime() + (Number(orderMainData.YanShiXieHuoFenZhongShu) * 60 * 1000),
          delayTime = wx.$util.formatDate(new Date(delay),'yyyy-MM-dd HH:mm');
        obj[`inputData.ZhiDingXieHuoJieShuShiJian`] = delayTime
      }

      this.setData(obj);
      wx.showLoading();
      this.wxLocation().then(res => {
        wx.hideLoading();
        let {address,location,formatted_addresses} = res.result;
        address = formatted_addresses && formatted_addresses.recommend || address;
        let inputData = {...this.data.inputData};
        inputData[`driver_${target}_addr`] = address
        inputData[`driver_${target}_longitude`] = location.lng
        inputData[`driver_${target}_latitude`] = location.lat;

        this.setData({
          address,location,
          inputData
          /*[`inputData.driver_${target}_addr`]: address,
          [`inputData.driver_${target}_longitude`]: location.lng,
          [`inputData.driver_${target}_latitude`]: location.lat,*/
        })
        resolve();
      },() =>{
        wx.hideLoading();
        wx.showModal({
          title: '定位服务未打开',
          content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
          confirmText: '确定',
          showCancel: false,
          success: (res) => {
            if(res.confirm) {
              wx.navigateTo({url:'/SlagCar/OpenLocationGuide/OpenLocationGuide'})
            }
          },
        });
      })

    })
  },

  //  字段变化
  bindChange(e){
    let {field,val,optItem} = e.detail,
      id = field.field_id || field.fieldName,
      type = field.type,
      obj = this.data.info,
      setObj = {};
    let inputData = {...this.data.inputData}

    if (type === 'num' || type === 'currency' || type === 'percent'){
      val = val ? val : null
    }

    // 泥头挖机号-填充挖机单位construction_excavator_client
    if (id === 'fill_excavator_no'){
      inputData.construction_excavator_client = optItem && optItem.Order_client_ID;
      setObj[`inputData.construction_excavator_client`] = optItem && optItem.Order_client_ID;
    }
    // 泥尾挖机号-填充挖机单位destination_excavator_client
    if (id === 'fill_excavator_no_end'){
      inputData.destination_excavator_client = optItem && optItem.Order_client_ID;
      setObj[`inputData.destination_excavator_client`] = optItem && optItem.Order_client_ID;
    }

    // 卸货图片
    if (id === 'driver_end_img') {
      // inputData.WuShuiYinSiJiJieShuZhaoPian = optItem && optItem.originImgs
      this.setEndPic(optItem && optItem.originFile)
    }
    //赋值
    this.setData({isEdit: true});
    inputData[id] = val;
    setObj[`inputData.${id}`] = val;
    // this.setData(setObj)
    this.setData({inputData})
    this.setData({isEdit: false});
    // this.data.inputData[id] = val;

  },


  //获取水印信息
  getWatermark(){
    return new Promise(resolve => {
      this.initData().then(() => {

        let {address,rowData,nowTime,inputData} = this.data,
          car = rowData['reference1_car;value'],
          // addr = inputData.ZhiDingXieHuoDiZhi || address,
          // time = inputData.ZhiDingXieHuoJieShuShiJian || nowTime;
          addr = address,
          time = nowTime;
        let arr = [{
          content: addr,
          font: '14px serif',
          position: {
            bottom: 20,
            left: 15
          }
        },
          {
            content: car,
            font: '24px serif',
            position: {
              bottom: 50,
              left: 15
            }
          },
          {
            content: time,
            font: '25px serif',
            position: {
              bottom: 80,
              left: 15
            }
          },
          /*{
            content: 'date',
            font: '26px serif',
            position: {
              bottom: 120,
              left: 30
            }
          },*/];
        resolve(arr)
      });
    })
  },
  // 指定卸货结束图片
  setEndPic(files){
    console.log(files);
    let {inputData,nowTime,rowData} = this.data;
    if (!inputData.ZhiDingXieHuoDiZhi){
      return
    }
    let car = rowData['reference1_car;value'],
      addr = inputData.ZhiDingXieHuoDiZhi,
      time = inputData.ZhiDingXieHuoJieShuShiJian || nowTime;
    let opts = [{
      content: addr,
      font: '14px serif',
      position: {
        bottom: 20,
        left: 15
      }
    },
      {
        content: car,
        font: '24px serif',
        position: {
          bottom: 50,
          left: 15
        }
      },
      {
        content: time,
        font: '25px serif',
        position: {
          bottom: 80,
          left: 15
        }
      },];
    let uploadFn = wx.$uploadReq,
      proArr = [],originArr = [],uploadImgs = [],originImgs = [];
    new Promise(resolve => {
      files.forEach(async (item,i )=> {

        wx.showLoading({title: '正在压缩图片',mask: true});

        await imgCompress(item,'',this).then(res => {
          originArr.push(uploadFn(res.tempFilePath, ))
        });
        await imgCompress(item,opts,this).then(res => {
          console.log(res.tempFilePath);
          proArr.push(uploadFn(res.tempFilePath, ))
          if (i === files.length-1){
            resolve();
          }
        });
      })
    }).then(() =>{
      wx.showLoading({title:'正在上传图片',mask: true})
      Promise.all([...proArr,...originArr]).then(res => {

        wx.showLoading({title:'正在判断图片长度',mask: true})
        let field_long = 0,
          errmsgArr = [];
        res.forEach((item,index) => {
          let { data, response, } = item,
            { errcode, errmsg} = response,
            { row, } = data
          if (errcode != 0) errmsgArr.push(errmsg)
          // if(errcode === 0 && row[0] && row[0].data) uploadImgs.push(row[0].data)

          if(errcode === 0 && row[0] && row[0].data) {
            let name = row[0].filename
            //240313 yan 增加判断字段长度
            if (field_long && (uploadImgs.join(',').length + name.length+1) > field_long) {
              wx.$toast('上传图片超出长度')
              return;
            }
            //240313 end
            index < proArr.length && uploadImgs.push(name)
            if (index >= proArr.length){
              originImgs.push(name)
            }
          }
        });
        wx.hideLoading();
        errmsgArr.length && wx.$toast(errmsgArr.join(','))
        //231215 end
        console.log(uploadImgs);
        console.log(originImgs);
        let {inputData } = this.data;
        inputData.ZhiDingXieHuoJieShuZhaoPian = uploadImgs && uploadImgs.join(',')
        inputData.WuShuiYinSiJiJieShuZhaoPian = originImgs && originImgs.join(',');
        this.setData({isEdit: true});
        this.setData({inputData})
        this.setData({isEdit: false});
      })
    })
  },

  //获取所有泥头
  getDeliveryAll(){
    wx.showLoading({mask: true});
    this.getCustomData('all_delivery').then(res => {
      wx.hideLoading();
      let deliveryList = res || [];
      this.setData({deliveryList});
    });
    this.getExceedDistance();
  },
  //获取所有泥尾
  getDestinationAll(){
    wx.showLoading({mask: true});
    this.getCustomData('all_destination').then(res => {
      wx.hideLoading();
      this.data.destinationAll = res || [];
    });
    this.getExceedDistance();
  },
  //获取超远距离
  getExceedDistance(){
    wx.showLoading({mask: true})
    this.getCustomData('all_parameter').then(res => {
      wx.hideLoading();
      let data = res || [],
        exceedDistance = 200; //默认200
      data.forEach(item =>{
        item.parameter_id === 'CS01' && (exceedDistance = Number(item.parameter_value));
      });
      this.setData({exceedDistance})
    });
  },
  //判断是否泥尾异常,id: 泥尾id
  abnormalDest(id){
    return new Promise((resolve,reject) => {
      let {destinationAll,location,exceedDistance,rowData} = this.data,
        destInfo = destinationAll.find(item => item.row_id == id);

      //当前经纬度与泥头经纬度一致且不是内转的
      if (rowData.driver_start_latitude == location.lat && rowData.driver_start_longitude == location.lng && rowData['reference1_goods;value'] !== '内转') {

        wx.showModal({
          title: '异常泥尾',
          content: '当前提交位置与泥头位置一致，请重新拍照上传',
          showCancel: false,
        });
        wx.hideLoading();
        this.data.loading = false;
        return
      }

      if (destInfo){
        let {destination_latitude,destination_longitude} = destInfo,
          to = `${destination_latitude},${destination_longitude}`,
          from = `${location.lat},${location.lng}`;
        if (!destination_latitude || !destination_longitude) {
          resolve(true)
          return
        }
        this.mapGetDistance(from,to).then((res) =>{
          let dis = res.result.elements[0],
          abnormal = dis.distance > exceedDistance;
          if (abnormal) {
            wx.hideLoading();
            wx.showModal({
              title: '异常泥尾',
              content: '当前提交位置异常，确定提交？',
              success: (res) => {
                if(res.confirm) {
                  wx.showLoading({mask: true})
                  resolve(true);
                }
              },
            })
          }else {
            resolve(false);
          }
          // resolve(dis.distance > exceedDistance);
        })
      }else {
        resolve(true)
      }
    })
  },
  //判断是否异常泥头，id: 泥头id
  abnormalDeli(id){
    return new Promise(resolve => {
      let {deliveryList,location,exceedDistance} = this.data,
        deliInfo = deliveryList.find(item => item.row_id == id);

      if (deliInfo){
        let {delivery_latitude,delivery_longitude} = deliInfo,
          to = `${delivery_latitude},${delivery_longitude}`,
          from = `${location.lat},${location.lng}`;
        if (!delivery_latitude || !delivery_longitude) {
          resolve(true)
          return
        }
        this.mapGetDistance(from,to).then((res) =>{
          let dis = res.result.elements[0],
            abnormal = dis.distance > exceedDistance;
          if (abnormal) {
            wx.hideLoading();
            wx.showModal({
              title: '异常泥头',
              content: '当前提交位置异常，确定提交？',
              success: (res) => {
                if(res.confirm) {
                  wx.showLoading({mask: true})
                  resolve(true);
                }
              },
            })
          }else {
            resolve(false);
          }


        })
      }else {
        resolve(true)
      }
    })
  },


  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false,) ? false : true;
      resolve(valid)
    })
  },

  //判断必填项 data:数据项，required必填项对象
  checkRequired(data,required){
    let flag = true;
    Object.keys(required).forEach(item => {
      let value = data[item]
      if (flag && ['',undefined,null].includes(value)){
        wx.$toast(required[item]);
        flag = false;
      }
    })
    return flag;
  },

  //预览照片
  previewImg(e){
    let {list,i} = e.currentTarget.dataset;
    list = list && list.split(',') || []
    let {  system_id,baseURL } = this.data,
      imgs = [];
    //231221 yan 修改 图片字段只返回文件名称，通过系统号拼接图片访问地址
    list.forEach(item => {
      let name = item.substring(item.lastIndexOf('/')+1);
      imgs.push(`${baseURL}/files/${system_id}/${name}`)
    });
    //231221 end
    wx.previewImage({
      current: imgs[i],
      urls: imgs
    })
  },

  //  获取当前位置
  wxLocation(){
    return new Promise((resolve,reject) => {
      // resolve({latitude:23.035508897569443 , longitude:113.11290771484374});
      //231227 yan 修改获取定位方法
      /*wx.getLocation({
        type: 'gcj02', // 比较精确
        success: (res) => {
          this.mapGeocoder(res).then(result => {
            resolve(result);
          })
        },
        fail: (res) =>{
          console.log(res);
          reject();
        }
      })*/

      wx.$getLocation().then(res =>{
        wx.showLoading({title: '正在转换位置信息',mask: true})
        this.mapGeocoder(res).then(result => {
          wx.hideLoading();
          resolve(result);
        })
      },reject)
    })
  },

  //腾讯地图api逆地址转换
  mapGeocoder(latlng){
    let url = 'map/tencent/ws/geocoder/location';
    let{latitude, longitude} = latlng;
    return new Promise(resolve => {
      wx.$post(2,url,{
        "key": config.mapKey,
        "location": `${latitude},${longitude}`,
        "get_poi": "",
        "poi_options": "",
        "output": "",
        "callback": ""
      },false,true).then(res =>{
        resolve(res)
      })
    })
  },
  //腾讯地图获取两点间距离
  mapGetDistance(from ,to){
    return new Promise(resolve => {
      let url = `map/tencent/ws/distance`,
        post = {
          "mode": "driving",
          from, to,
          // "output": "string",
          // "callback": "string",
          "key": config.mapKey
        };
      wx.$post(2,url,post,false,true).then(res =>{
        resolve(res)
      })
    })
  },

  // 250427 获取订单主表信息
  getOrderMain(data) {
    return new Promise(resolve => {
      let {rowData} = this.data,
        rdata = data || rowData,
        where = [{CompareValue: rdata.reference1_muck_order_main, CompareWith: "muck_order_main.row_id", Operator: "=", or: 0}],
        fieldList = ['row_id','XuYaoTianTuZhiWeiZhi','TuZhiWeiZhiLieBiao','ZhiDingXieHuoDiZhi','ZhiDingXieHuoJingDu','ZhiDingXieHuoWeiDu','ZhiDingXieHuoDiZhiXiaoNaChang','YanShiXieHuoFenZhongShu'];
      this.getCustomData('muck_order_main',where,fieldList.join(',')).then(row =>{
        this.data.orderMainData = row && row[0];
        resolve()
      })
    })
  },

  //获取diy数据
  getCustomData(table_id,where,field_list){
    let url = 'DynamicQuery/query_dynamic_v3';
    return new Promise(resolve => {
      let post = {limit: 0, page: 1, table_id,obj: `${table_id}.row_id`,field_list}
      where && (post.SearchWhere = {filters: where,type: 'and'});
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) {
          resolve()
          return;
        }
        resolve(res.data.row)
      })
    })
  },

  //提交审核
  bindSubmitApprove(){
    wx.showModal({
      title: '提交审核',
      content: `确定提交审核？`,
      success: async (res) => {
        if(res.confirm) {
          let {rowData} = this.data;
          this.getApproveProcess().then(process_id => {
            wx.showLoading({mask: true})
            this.updateApprove(rowData.row_id,'提交').then(() => {
              wx.$toast('提交成功');
              this.getRowData();
            })
          })
        }
      },
    })
  },
  //获取审批号
  getApproveProcess(){
    return new Promise(resolve => {
      let url = 'Approval_process/query_approval_process',
        post = {
          page: 1,
          oby: "process_id desc",
          limit: 1,
          SearchWhere: [
            {
              CompareValue: 'muck_waybill_main',
              CompareWith: 'table_id',
              Operator: '=',
              or: 0
            },
            {
              CompareValue: true,
              CompareWith: 'status',
              Operator: '=',
              or: 0
            },
          ]
        },
        {process_id} = this.data;
      if (process_id){
        resolve(process_id);
        return
      }
      wx.showLoading({mask: true});
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        if (res.data.row[0]) process_id = res.data.row[0].process_id;
        this.data.process_id = process_id;
        resolve(process_id);
        wx.hideLoading();
      })
    })
  },

  //提交审批
  updateApprove(rid,state){
    let {process_id} = this.data,
      url = 'Approval_process/update_approval_process_log',
      post = {
        "table_id": "muck_waybill_main",
        "row_id": rid,
        "sh_state": state,
        "next_sh_id":"",
        "next_sh_name":"",
        "sh_mark":""
      };
    if (state === '提交')post.process_id = process_id;
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve();
      })
    })
  },

  // 显示取消申请
  showCancelApply(){
    this.setData({
      cancelShow: true
    });
    this.getCancelUser().then(res =>{
      this.setData({
        ['cancelField[2].optionList']: res
      })

    })
  },
  // 申请取消运单字段变化
  bindCancelFieldChange(e) {
    let {field,val,optItem} = e.detail,
      id = field.field_id || field.fieldName;

    //审核取消接收员号,填充审核取消接收员名
    if (id === 'ShenHeQuXiaoJieShouYuanMing') {
      let name = optItem;
      this.data.cancelData.ShenHeQuXiaoJieShouYuanHao = name
    }
    //赋值
    this.data.cancelData[id] = val
  },
  // 确定提交取消运单申请
  bindConfirmApply() {
    let {cancelData,rowData} = this.data;
    let post = {...cancelData,row_id: rowData.row_id}
    wx.showLoading({mask: true,title: '正在提交'});
    wx.$post(5,'ZTAuth/ApplyCancelWaybill',post).then(res =>{
      wx.hideLoading();
      if(res.errcode != 0) return;
      wx.$toast('已成功登记申请');
      this.setData({cancelShow: false});
      this.getRowData();
    })
  },

  // 获取审批取消运单人员
  getCancelUser(){
    return new Promise(resolve => {
      if (this.data.cancelUserList){
        resolve(this.data.cancelUserList);
        return
      }
      wx.showLoading({mask: true});
      wx.$get(5,'ZTAuth/AuditCancelWaybillUser').then(res =>{
        wx.hideLoading();
        if (res.errcode != 0) return;
        let data = res.data.row || [];
        this.data.cancelUserList = data;
        resolve(data);
      })
    })
  },


  //  获取权限列表
  getAuthorityList(fid, pid, rid){
    return new Promise((resolve, reject) => {
      let post = {
        user_id: wx.getStorageSync('user_id'),
        function_id: fid,
        pare_id: pid || '',
        row_id: rid,
      }
      wx.$post(4, 'QX/PRO_QX_list', post).then(res => {
        if(res.errcode !== 0) return
        res = res.data
        let list = res.row || [];
        resolve(list)
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let user_type = wx.getStorageSync('user_type');
    this.setData({user_type})
    let {row_id} = options;
    this.data.row_id = row_id;
    this.getRowData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.getSetting({
      success(res){
        if (!res.authSetting['scope.userLocation']){
          console.log('未打开定位服务');
          wx.getLocation({
            type: 'gcj02', // 比较精确
            success: (res) => {
              console.log(res);
            },
            fail: (res) =>{
              wx.showModal({
                title: '定位服务未打开',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                confirmText: '去开启',
                success: (res) => {
                  if(res.confirm) {
                    wx.openSetting();
                  }
                },
              });
            }
          })

        }else {
          const systemSetting = wx.getSystemSetting();
          if (systemSetting.locationEnabled === false) {
            wx.showModal({
              title: '定位服务未打开',
              content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
              confirmText: '确定',
              showCancel: false,
              success: (res) => {
                if(res.confirm) {
                  wx.navigateTo({url:'/SlagCar/OpenLocationGuide/OpenLocationGuide'})
                }
              },
            })
          }
        }

      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
